package com.ksc.storekeeper.server.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ksc.storekeeper.server.entities.Product;
import com.ksc.storekeeper.server.repositories.ProductRepository;
import com.ksc.storekeeper.shared.dto.ProductDTO;
import com.ksc.storekeeper.shared.rpc.ProductService;
import com.ksc.storekeeper.shared.utils.conversion.ConversionUtils;

public class ProductServiceImpl implements ProductService {

	private final ProductRepository productRepository;

	public ProductServiceImpl(ProductRepository productRepository) {
		this.productRepository = productRepository;
	}

	@Override
	public void saveProduct(ProductDTO productDTO) {
		Product product = new Product();
		ConversionUtils.convert(productDTO, product);
		product.setCreated(new Date());
		this.productRepository.save(product);
	}

	@Override
	public List<ProductDTO> searchProductByCategory(final String valueId) {
		List<ProductDTO> productDTOs = new ArrayList<ProductDTO>();
		for (Product product : productRepository.findByCategory(valueId)) {
			ProductDTO productDTO = new ProductDTO();
			ConversionUtils.convert(product, productDTO);
			productDTOs.add(productDTO);
		}
		return productDTOs;
	}

	@Override
	public ProductDTO searchProductByCode(String code) {
		ProductDTO productDTO = new ProductDTO();
		ConversionUtils.convert(productRepository.findByCode(code), productDTO);
		return productDTO;
	}

	@Override
	public List<ProductDTO> getAllProducts() {
		final Iterable<Product> productItr = this.productRepository.findAll();
		List<ProductDTO> products = new ArrayList<ProductDTO>();
		for (Product product : productItr) {
			ProductDTO productDTO = new ProductDTO();
			ConversionUtils.convert(product, productDTO);
			products.add(productDTO);
		}
		return products;
	}

	@Override
	public ProductDTO getProductById(Long id) {
		ProductDTO productDTO = new ProductDTO();
		ConversionUtils.convert(this.productRepository.findOne(id), productDTO);
		return productDTO;
	}

}
